<template>
  <div class="page" style="height: 90vh;overflow: hidden">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-cascader
        placeholder="搜索组织"
        :show-all-levels="false"
        change-on-select
        v-model="selectedOrg"
        clearable
        :options="datas"
        ref="refHandle"
        @change="changeDept"
        filterable
      ></el-cascader>
    </div>
    <div class="page_main" id="pageBox"  style="height: 80vh;overflow: scroll">
      <div v-for="(item,index) in datas"   :key="item.id">
        <div  id="tree_wrap_org">
          <vue2-org-tree
            name="test"
            :data="datas[index]"
            :horizontal="horizontal"
            :label-class-name="labelClassName"
            :render-content="renderContent"
            collapsable
            @on-expand="onExpand"
            @on-node-click="onNodeClick"
          />
        </div>
        <el-divider></el-divider>
      </div>

    </div>
    <!-- 新增编辑弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="isShowDialog"
      :before-close="clearValidate"
      width="600px">
      <el-row>
        <el-col :span="12"></el-col>
      </el-row>
      <!-- 具体form表单 -->
      <el-form label-position="right" ref="form" :rules="rules" :model="currentRow" label-width="100px"
               class="form_width-200">
        <el-form-item label="组织名称" prop="name">
          <el-input class="init_input-limit" v-model.trim="currentRow.name" placeholder="输入组织机构名称" maxlength="20"
                    show-word-limit></el-input>
        </el-form-item>
        <el-form-item v-if="!isEditStatus" label="机构编号" prop="code">
          <el-input class="init_input-limit" v-model.trim="currentRow.code" placeholder="输入机构编号" maxlength="20"
                    show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="单位类型" prop="industry">
          <el-select v-model="currentRow.unitType" clearable placeholder="请选择单位类型" >
            <el-option v-for="item in EnumUnitTypeList" :key="item.code" :label="item.name"
                       :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="userName">
          <el-input class="init_input-limit" v-model.trim="currentRow.userName" placeholder="输入负责人名称" maxlength="20"
                    show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="userPhone">
          <el-input class="init_input-limit" v-model.trim="currentRow.userPhone" placeholder="输入负责人电话" maxlength="20"
                    show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="clearValidate">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {
    getLocalStorageItem,
  } from "@/utils/storage-helper";
  import {ORGANIZATION_TREE} from '@/utils/constant'
  import {getOrganizationTree} from '@/services/model/user'
  import {setLocalStorageItem} from '@/utils/storage-helper'
  import {
    orgQuery,
    orgUpdate,
    orgAdd,
  } from '@/services/model/authority-mgmt'
  import Format from '@/utils/format'
  import {filterEmpty} from '@/services/request'
  import cryptoJs from "crypto-js";
  import Enums from '@/utils/enums'

  // 初始的搜索参数
  export default {
    data() {
      return {
        selectDept: "", //选中的单个组织id
        selectedOrg: [], //选中的组织treeid
        selectedOrgList:[],
        horizontal: true,
        collapsable: false,
        expandAll: true,
        labelClassName: "bg-none",
        datas:[],
        form: {
          page: 1,
          pageSize: 10,
        },
        rules: {
          name: {required: true, message: '请输入部门名称'},
          // code: {required: true, message: '请输入部门编号'},
        },
        tableList: [],
        allTotal: 0,
        isShowDialog: false, // 是否显示弹窗
        currentRow: {}, // 新增数据
        // indeterminate 属性用以表示 checkbox 的不确定状态，一般用于实现全选的效果
        EnumUnitTypeList: [],
        node_had: {
          childNodes: [],
        },
        resolve_had: '',
        tree_had: '',
        tempOrgId: '',
        nodeList: [],
      }
    },
    mixins:[Enums],
    watch: {
      //任选一级时，自动关闭选项框
      selectedOrg() {
        if (this.$refs.refHandle) {
          this.$refs.refHandle.dropDownVisible = false; //监听值发生变化就关闭它
        }
      }
    },
    computed: {
      // 弹窗的title
      dialogTitle() {
        return this.currentRow.id ? '编辑组织' : '新增组织'
      },
      // true  为编辑   false  accountQueryRoleList
      isEditStatus() {
        return !!this.currentRow.id
      },
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer), 'yyyy-MM-dd hh:mm:ss')
      },
      // 0正常，1锁定
      getStatusBtnMap(type) {
        return type ? '停用' : '启用'
      }
    },
    methods: {
      //选项处理，tree展开项
      findDeptName(list, index) {
        list.map((x) => {
          if (x.value === this.selectedOrg[index]) {
            this.$set(x, "expand", true); //控制展开与否
            if (!x.children) {
              return;
            }
            index++;
            this.findDeptName(x.children, index);
          }
          else {
            this.$set(x, "expand", false); //
          }
        });
      },
      //点击选项执行的方法，可以用于跳转到其他链接，注意一定要写协议头
      onNodeClick(e, data) {
      },
      //搜索组织架构
      changeDept() {
        this.findDeptName(this.datas, 0);
      },
      //决定样式
      renderContent(h, data) {
        return (
          < span
        style = "min-width:10vw;height:5vw;display:block;border-radius:3px;" >
        <dd class="card_title">  <el-popover placement="top"
        trigger="click">
          <div style="display: flex;justify-content: space-between;align-items: center;width:10vw;height:5vw;flex-wrap: wrap">
          <p style="width:35%;fontSize:1.2vh;fontWeight:600"> 组织名称：</p>
        <p style="width:65%;fontSize:1.2vh"> {data.name}</p>
          <p style="width:35%;fontSize:1.2vh;fontWeight:600"> 单位类型：</p>
        <p style="width:65%;fontSize:1.2vh"> {data.unitTypeName}</p>
          <p style="width:35%;fontSize:1.2vh;fontWeight:600"> 负责人：</p>
        <p style="width:65%;fontSize:1.2vh"> {data.userName}</p>
          <p style="width:35%;fontSize:1.2vh;fontWeight:600"> 手机号码：</p>
        <p style="width:65%;fontSize:1.2vh"> {data.userPhone}</p>
          </div>
          <i slot="reference"
      class="header-icon el-icon-info"
        style="color:#1990FE;fontSize:2vh"
          ></i>
          </el-popover>{ data.label}</dd>
          < dd>
          <button class="btn_add" on-click={() => this.handleAdd(data)} style="margin-right:20px">添加子组织</button>
          <button class="btn_compile"  on-click={() => this.handleEdit(data)} >编辑</button>
        </dd>
        < /span>
      )
      },
      //展开按钮
      onExpand(e, data) {
        this.selectedOrgList.push(data)
        this.selectedOrg.push(data.value)
        this.selectedOrgList.map((x,index)=>{
          if(index+1!==x.level){
            this.selectedOrg.splice(x.level-1)
            this.selectedOrgList.splice(x.level-1)//把重复的删除掉
            this.selectedOrgList.push(data)
            this.selectedOrg.push(x.value)
              return
            }
          }
        )
        if ("expand" in data) {
          data.expand = !data.expand;
          if (!data.expand && data.children) {
            this.collapse(data.children);
            if(this.selectedOrg.indexOf(data.value) > -1){
              this.selectedOrg.splice(this.selectedOrg.length-1,1) //删除数组里面重复的
            }
          }
        } else {
          this.$set(data, "expand", true);
        }
      },
      //收起处理
      collapse(list) {
        let selectedOrg=[]
        selectedOrg= this.selectedOrg.filter(x=>x!==list.parentId)
        var _this = this;
        list.forEach(function (child) {
          if (child.expand) {
            child.expand = false;
          }
          child.children && _this.collapse(child.children);
        });
      },
      //默认展开
      toggleExpand(data, val) {
        var _this = this;
        if (Array.isArray(data)) {
          data.forEach(function (item) {
            _this.$set(item, "expand", val);
            if (item.children) {
              _this.toggleExpand(item.children, val);
            }
          });
        } else {
          this.$set(data, "expand", val);
          if (data.children) {
            _this.toggleExpand(data.children, val);
          }
        }
      },
      // 关闭弹窗之前清楚表单校验提示
      clearValidate() {
        this.$refs.form.clearValidate()
        this.isShowDialog = false
      },
      // 表单提交
      validateForm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.currentRow = filterEmpty(this.currentRow)
            this.submitData()
          }
        })
      },
      // 新增编辑提交数据
      async submitData() {
        // 根据ID判断使用新增还是编辑
        let action = this.currentRow.id ? orgUpdate : orgAdd
        let res = await action(this.currentRow)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: this.currentRow.id ? '修改成功' : '添加成功'
          })
          this.getOrganizationTree()
          this.isShowDialog = false
          if( !this.currentRow.id){
            this.currentRow.id=res.data
            this.currentRow.label=this.currentRow.name
             let deptTreeIdList= this.currentRow.deptTreeId.split('-')
             this.currentRow.deptTreeId=deptTreeIdList.join('-')
          }
         let DATALIST=JSON.parse(JSON.stringify(this.datas))
          if(action==orgUpdate){
            this.datas= this.changeDatas(DATALIST,this.currentRow,0,'编辑')
          }else {
          this.datas= this.changeDatas(DATALIST,this.currentRow,0,'新增')
          }
          //刷新组织架构缓存

          return
        }
      },
      //处理数据
      changeDatas(datas,list, index,type) {
        let deptTreeIdList= list.deptTreeId.split('-')
        datas.map((x,index1)=>{
          if(x.id===deptTreeIdList[index]){
            //编辑
            if(type=='编辑'){
              if(x.id===deptTreeIdList[deptTreeIdList.length-1]){  //如果等deptTreeIdList最后一个 就做判断
                this.$set( datas, index1, list )
                this.$forceUpdate()
                return;
              }
            }
          if(type=='新增'){
            x.children.push(list)
            this.$forceUpdate()
          }
            index++;
            this.changeDatas(x.children, list,index,type);
            return;
          }
        })
        return datas
      },
      //给数据增加level
      dataLevel(list, index) {
        list.map((x) => {
         let list= x.deptTreeId.split('-')
            this.$set(x, "level", list.length); //控制展开与否
            if (!x.children) {
              return;
            }
            index++;
            this.dataLevel(x.children, index);
        });
        return list
      },
      //添加组织架构缓存
      async getOrganizationTree() {
        let res = await getOrganizationTree();
        this.datas=res.data
        //缓存一天过期
        setLocalStorageItem(ORGANIZATION_TREE, res.data, 1)
      },
      // 新增数据
      handleAdd(row) {
        this.currentRow = {
          parentId: row ? row.id : null,
          deptTreeId:row ? row.deptTreeId : null,
          unitType: row ? row.unitType : 2
        }
        this.isShowDialog = true
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      },
      /**
       * row  当前操作行的对象
       */
      handleEdit(row) {
        this.currentRow={}
        this.currentRow = {...row}

        this.isShowDialog = true
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      },
    },
    mounted() {
      // 启用状态枚举
      this.queryDictList(['EnumSysFlag','EnumUnitType'], ['EnumSysFlagList', 'EnumUnitTypeList'])
     this.getOrganizationTree()
      // this.datas=this.dataListS
      this.dataLevel(this.datas,0)
      this.$forceUpdate()
    },
    activated() {

    }
  }
</script>
<style lang="less" scoped>

  /deep/ .el-table {
    .cell {
      text-align: left !important;
    }
  }

  .user_status {
    &::before {
      content: '';
      margin-right: 6px;
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: #969997;
    }

    &.active::before {
      background-color: #0DC26B;
    }
  }

  /deep/ .relate_checkbox {
    .el-checkbox {
      margin-bottom: 30px;

      .el-checkbox__label {
        width: 100px;
      }
    }
  }

  /deep/ .dialog_area {
    .el-dialog__header {
      padding-bottom: 0;
    }
  }

  .area_filter {
    .el-select {
      margin-right: 10px;
    }
  }

  .area_choose {
    display: flex;
    margin-top: 30px;

    .choose_left {
      flex-shrink: 0;
      width: 330px;
      border-right: 1px solid #E4E7ED;
      padding-right: 30px;
    }

    .choose_right {
      padding-left: 30px;
      flex-shrink: 0;
      width: 330px;
    }

    .choose_top {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 12px;
      border-bottom: 1px solid #EBEEF5;

      span {
        color: #303133;
        font-weight: bold;
        font-family: PingFangSC-Medium, PingFang SC;
      }

      .top_right {
        color: #606266;

        &.el-button {
          padding: 0;
        }
      }
    }
  }

  .choose_ul {
    padding-top: 16px;
    height: 100%;

    .choose_li {
      cursor: pointer;
      padding: 0 12px 0 9px;
      width: 100%;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      em {
        display: flex;
        align-items: center;
        font-size: 13px;
        color: #303133;

        .el-icon-check {
          color: #0DC26B;
          margin-right: 5px;
        }
      }

      i {
        font-size: 15px;
      }

      .el-icon-circle-plus-outline {
        display: none;
        color: #0DC26B;
      }

      .el-icon-circle-close {
        display: none;
        color: #F56C6B;
      }

      &:hover {
        background-color: #F2F6FC;

        i {
          display: block;
        }
      }

      &.disable {
        em {
          color: #C0C4CC;
        }

        .el-icon-circle-plus-outline {
          display: none !important;
        }
      }
    }
  }

  .margin_l-16 {
    margin-left: 16px;
  }

  .init_input-limit /deep/ input {
    padding-right: 45px;
  }

  .item_tag {
    margin-left: 6px;

    &:first-child {
      margin-left: 0;
    }
  }
</style>

<style>
  #tree_wrap_org{
    overflow: auto;
    text-align: center;
    box-sizing: border-box;
    padding: 1vw ;
    width: 100vw;
  }
  #tree_wrap_org .card_wrap {
    display: flex;
  }

  #tree_wrap_org .card_item {
    box-sizing: border-box;
    padding: 16px 10px 10px 10px;
    width: 107px;
    height: 131px;
    border-radius: 8px;
    position: relative;
  }

  #tree_wrap_org .card_title {
    height: 25px;
    height: 35px;
    word-wrap: break-word;
    word-break: normal;
    white-space: normal;
    font-family: MicrosoftYaHei;
    font-size: 14px;

    text-align: left;
  }

  #tree_wrap_org .circle_r {
    display: inline-block;
    box-sizing: border-box;
    width: 16px;
    height: 16px;
    border: 1px solid #D3E0EE;
    border-radius: 50%;
    position: absolute;
    left: 16px;
    bottom: 10px;
    cursor: pointer;
    z-index: 2;
  }

  #tree_wrap_org .activeCard {
    border-width: 4px;
  }

  #tree_wrap_org .firstItem {
    background-color: #1BC5BD;
  }

  #tree_wrap_org .firstItem::after {
    content: "";
    background: url(/img/card-1.2af9f09a.svg) no-repeat right bottom;
    opacity: 0.5;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
  }

  #tree_wrap_org .lastItem {
    background-color: #00CFE8;
  }

  #tree_wrap_org .lastItem::after {
    content: "";
    background: url(/img/card-2.577efdaf.svg) no-repeat right bottom;
    opacity: 0.5;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
  }

  #tree_wrap_org .add_btn {
    line-height: 131px;
    font-size: 26px;
  }

  #tree_wrap_org .add {
    color: #4C6072;
    cursor: pointer;
    margin-left: 10px;
  }
</style>
<style lang="less" scoped>
  #tree_wrap_org{
    width: 100%;
    height: 100%;
  }
  // org-tree样式
  .org-tree-container {
    display: inline-block;
    width: 100%;
    box-sizing: border-box;
    overflow: auto;
    background-color: #fff;
    text-align: center;
  }

  .org-tree {
    display: table;
    text-align: center;

    &:before, &:after {
      content: '';
      display: table;
    }

    &:after {
      clear: both;
    }
  }

  .org-tree-node,
  .org-tree-node-children {
    position: relative;
    margin: 0;
    padding: 0;
    list-style-type: none;

    &:before, &:after {
      transition: all .35s;
    }
  }
  .org-tree-node-label {
    position: relative;
    display: inline-block;

    .org-tree-node-label-inner {
      padding: 0px;
      text-align: center;
      border-radius: 3px;
      //box-shadow: 0 1px 5px rgba(0, 0, 0, .15);
    }
  }
  .org-tree-node-btn {
    position: absolute;
    top: 100%;
    left: 50%;
    width: 20px;
    height: 20px;
    z-index: 10;
    margin-left: -11px;
    margin-top: 9px;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 50%;
    box-shadow: 0 0 2px rgba(0, 0, 0, .15);
    cursor: pointer;
    transition: all .35s ease;

    &:hover {
      background-color: #e7e8e9;
      transform: scale(1.15);
    }

    &:before, &:after {
      content: '';
      position: absolute;
    }

    &:before {
      top: 50%;
      left: 4px;
      right: 4px;
      height: 0;
      border-top: 1px solid #ccc;
    }

    &:after {
      top: 4px;
      left: 50%;
      bottom: 4px;
      width: 0;
      border-left: 1px solid #ccc;
    }

    &.expanded:after {
      border: none;
    }
  }
  .org-tree-node {
    padding-top: 20px;
    display: table-cell;
    vertical-align: top;

    &.is-leaf, &.collapsed {
      padding-left: 10px;
      padding-right: 10px;
    }

    &:before, &:after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 50%;
      height: 19px;
    }

    &:after {
      left: 50%;
      border-left: 1px solid #ddd;
    }

    &:not(:first-child):before,
    &:not(:last-child):after {
      border-top: 1px solid #ddd;
    }

  }
  .collapsable .org-tree-node.collapsed {
    padding-bottom: 30px;

    .org-tree-node-label:after {
      content: '';
      position: absolute;
      top: 100%;
      left: 0;
      width: 50%;
      height: 20px;
      border-right: 1px solid #ddd;
    }
  }
  .org-tree > .org-tree-node {
    padding-top: 0;

    &:after {
      border-left: 0;
    }
  }
  .org-tree-node-children {
    padding-top: 20px;
    display: table;

    &:before {
      content: '';
      position: absolute;
      top: 0;
      left: 50%;
      width: 0;
      height: 20px;
      border-left: 1px solid #ddd;
    }

    &:after {
      content: '';
      display: table;
      clear: both;
    }
  }

  .horizontal {
    .org-tree-node {
      display: table-cell;
      float: none;
      padding-top: 0;
      padding-left: 20px;

      &.is-leaf, &.collapsed {
        padding-top: 10px;
        padding-bottom: 10px;
      }

      &:before, &:after {
        width: 19px;
        height: 50%;
      }

      &:after {
        top: 50%;
        left: 0;
        border-left: 0;
      }

      &:only-child:before {
        top: 1px;
        border-bottom: 1px solid #ddd;
      }

      &:not(:first-child):before,
      &:not(:last-child):after {
        border-top: 0;
        border-left: 1px solid #ddd;
      }

      &:not(:only-child):after {
        border-top: 1px solid #ddd;
      }

      .org-tree-node-inner {
        display: table;
      }

    }

    .org-tree-node-label {
      display: table-cell;
      vertical-align: middle;
    }

    &.collapsable .org-tree-node.collapsed {
      padding-right: 30px;

      .org-tree-node-label:after {
        top: 0;
        left: 100%;
        width: 20px;
        height: 50%;
        border-right: 0;
        border-bottom: 1px solid #ddd;
      }
    }

    .org-tree-node-btn {
      top: 50%;
      left: 100%;
      margin-top: -11px;
      margin-left: 9px;
    }

    & > .org-tree-node:only-child:before {
      border-bottom: 0;
    }

    .org-tree-node-children {
      display: table-cell;
      padding-top: 0;
      padding-left: 20px;

      &:before {
        top: 50%;
        left: 0;
        width: 20px;
        height: 0;
        border-left: 0;
        border-top: 1px solid #ddd;
      }

      &:after {
        display: none;
      }

      & > .org-tree-node {
        display: block;
      }
    }
  }
</style>


